<template>
  <div class="user_address">
    <div class="user_main table_lists">
      <div class="block_title">
        <span><div class="btn" @click="handleAddAddress">新增地址</div></span>
        收货地址
      </div>
      <div class="x20"></div>
      <div class="address_list" v-if="true">
        <ul>
          <li v-for="(v, k) in addressStore.addressList" :key="k">
            <div class="pos_img"><img :src="v.isDefault == 1 ? '/src/assets/Home/address_pos2.png' : '/src/assets/Home/address_pos.png'" alt="" /></div>
            <div class="name">{{ v.name }}</div>
            <div class="area_info">
              {{ v.allAddress }} <em style="font-weight: bold; margin-left: 10px">({{ v.phone }})</em>
            </div>
            <div class="handle">
              <span v-if="!v.isDefault" @click="addressStore.setDefaultAddress(v.id, queryParams)">设置默认</span>
              <em v-if="!v.isDefault">|</em>
              <span @click="handleUpdate(v)">编辑</span>|<span>删除</span>
            </div>
          </li>
        </ul>
      </div>
      <!--      <el-empty v-else />-->

      <div class="fy">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          background
          layout="prev, pager, next"
          :total="addressStore.total"
          @current-change="addressStore.getAddressList(queryParams)"
        />
      </div>
    </div>

    <!-- 新增.编辑 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500">
      <el-form ref="addressFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="form.name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="地址信息" prop="districtCode">
          <el-cascader v-model="form.region" :options="options" :props="{ label: 'name', value: 'code' }" @change="handleChange" />
        </el-form-item>
        <el-form-item label="街道地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="详细地址" prop="fullAddress">
          <el-input v-model="form.fullAddress" />
        </el-form-item>
        <!--        <el-form-item label="是否默认地址" prop="isDefault">-->
        <!--          <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" @change="changeStatus" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, toRefs } from 'vue';
import { updateAddressApi, addAddressApi, getAddressApi } from '@/api/user/address';
import { useUserStore } from '@/store';
import { getRegionListApi } from '@/api/user/region';
import { ElMessage } from 'element-plus';
import { useAddressStore } from '@/store/modules/address';

const userStore = useUserStore();
const options = ref([]);
const addressFormRef = ref<any>();
const buttonLoading = ref(false);
const addressStore = useAddressStore();
const initFormData: any = {
  userId: userStore.user.userId,
  name: '',
  phone: '',
  tagName: '',
  provinceCode: '',
  cityCode: '',
  districtCode: '',
  address: '',
  fullAddress: '',
  isDefault: 0,
  region: []
};
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: userStore.user.userId
  },
  rules: {
    name: [{ required: true, message: '收货人必填', trigger: 'blur' }],
    phone: [
      { required: true, message: '电话必填', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    districtCode: [{ required: true, message: '必须选择', trigger: 'c' }],
    address: [{ required: true, message: '请填写街道地址', trigger: 'blur' }],
    fullAddress: [{ required: true, message: '请填写详细地址', trigger: 'blur' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
const dialog = reactive({
  title: '增加地址',
  visible: false
});

const handleClose = () => {
  dialog.visible = false;
  reset();
};
const reset = () => {
  form.value = { ...initFormData };
};
const getRegionList = async () => {
  const res = await getRegionListApi();
  options.value = res.data;
};
/*新增收货地址*/
const handleAddAddress = () => {
  dialog.visible = true;
  getRegionList();
};
/*修改收货地址*/
const handleUpdate = async (row?: any) => {
  reset();
  await getRegionList();
  const _id = row?.id;
  const res: any = await getAddressApi(_id);
  // 赋值
  form.value.region = [res.data.provinceCode, res.data.cityCode, res.data.districtCode];
  Object.assign(form.value, { ...res.data });
  dialog.visible = true;
  dialog.title = '修改收货地址';
};
/*TODO 获取switch值 暂时不用此功能*/
// const changeStatus = (value: any) => {
//   form.value.isDefault = value;
// };
/*获取省市区组件*/
const handleChange = (value: any) => {
  console.log(value);
  form.value.provinceCode = value[0]; //省
  form.value.cityCode = value[1]; //市
  form.value.districtCode = value[2]; //区
};

/*提交*/
const submitForm = () => {
  addressFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      console.log(form.value);
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAddressApi(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAddressApi(form.value).finally(() => (buttonLoading.value = false));
      }
      ElMessage.success('操作成功');
      dialog.visible = false;
      // await getAddressList();
    }
  });
};
onMounted(() => {
  addressStore.getAddressList(queryParams.value);
});
</script>
<style lang="scss" scoped>
.address_list {
  margin-bottom: 30px;

  ul li {
    border-bottom: 1px solid #efefef;
    padding: 20px 0;
    position: relative;
    padding-left: 42px;

    &:first-child {
      padding-top: 0;

      .pos_img {
        left: 0;
        top: 6px;
      }

      .handle {
        top: 10px;
      }
    }

    .name {
      font-size: 16px;
      font-weight: bold;
    }

    .pos_img {
      position: absolute;
      left: 0;
      top: 26px;
    }

    .handle {
      position: absolute;
      right: 0;
      top: 28px;
      cursor: pointer;

      span {
        margin: 5px;

        &:hover {
          color: #ca151e;
        }
      }
    }
  }
}
</style>
